package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryList() {
        String key = "cache:shopType";
        //1.首先查redis中是否存在列表
        String shopType = stringRedisTemplate.opsForValue().get(key);
        //2.存在，直接将json字符串转换成列表返回
        if(!StrUtil.isBlank(shopType)){
            List<ShopType> shopList1;
            shopList1 = JSONUtil.toList(shopType,ShopType.class);
            return Result.ok(shopList1);
        }
        //3.不存在，则查询数据库
        List<ShopType> shopList1 = list();
        //4.如果数据库中不存在
        if(shopList1 == null){
            //5.提示错误信息
            return Result.fail("店铺类型不存在");
        }
        //6.存在则将数据存入redis中
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shopList1));
        //7.返回
        return Result.ok();
    }
}
